package com.wcl.demo.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * Created by dllo on 15/10/30.
 */
public class HanZiPinYinTranslate {

    /****
     * 将输入的汉字转化为拼音
     * 返回一个字的拼音
     * 带音调的
     */
    public static String translateToPinYin(char hanzi) {
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITH_TONE_MARK);
        //format.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);
        String[] pinyinArray = null;

        try {
            if (hanzi >= 0x4e00 && hanzi <= 0x9fa5) {
                pinyinArray = PinyinHelper.toHanyuPinyinStringArray(hanzi, format);
            }
        } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
            badHanyuPinyinOutputFormatCombination.printStackTrace();
        }
        //将获取到的拼音返回
        return  pinyinArray[0];
    }
    public static String translateToPinYin(String hanzi){
        String pinyin = "";
        for (int i = 0; i < hanzi.length(); i++) {
            char first = hanzi.charAt(i);
            pinyin += translateToPinYin(first);
        }
        return pinyin;
    }
    //汉字转拼音不带音调
    public static String getFirstSpell(String chinese) {
        String a = "";
        char[] arr = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] > 128){
                try {
                    a += PinyinHelper.toHanyuPinyinStringArray(arr[i],defaultFormat)[0];

                } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
                    badHanyuPinyinOutputFormatCombination.printStackTrace();
                }
            }else {
                a += arr[i];
            }
        }
        return a;

    }
}
